﻿namespace Nomo.TcpModule
{
    /// <summary>
    /// 在数据前面加上以 4 个字节表示的真实数据长度的封包器。
    /// </summary>
    public class LengthPrefixPacker : IPacker
    {
        void IPacker.Init() { }

        void IPacker.Pack(ref byte[] bytes)
        {
            if (bytes == null)
            {
                bytes = new byte[0];
            }

            var length = bytes.Length;

            using (var stream = new CoreModule.UtilityStream(4 + length))
            {
                stream.Write(System.Net.IPAddress.HostToNetworkOrder(length));
                stream.Write(bytes, 0, bytes.Length);
                bytes = stream.ToArray();
            }
        }
    }
}
